package com.wangxin.study8.parallelstreams;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName ParallelStreamsMain
 * @Description Stream有串行和并行两种，
 * 串行Stream上的操作是在一个线程中依次完成，
 * 而并行Stream则是在多个线程上同时执行。
 * @Author jojo.wang
 * @Date 2019-04-25 15:51
 * @Version 1.0
 **/
public class ParallelStreamsMain {
    public static void main(String[] args) {
        int max = 1000000;
        List<String> values = new ArrayList<>(max);
        for (int i = 0; i < max; i++) {
            UUID uuid = UUID.randomUUID();
            values.add(uuid.toString());
        }
        Sequential(values);

        Parallel(values);
    }

    public static void Sequential(List<String> values){
        long t0 = System.nanoTime();
        long count = values.stream().sorted().count();
        System.out.println(count);
        long t1 = System.nanoTime();

        long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
        System.out.println(String.format("sequential sort took: %d ms", millis));
    }

    public static void Parallel(List<String> values){
        long t0 = System.nanoTime();
        long count = values.parallelStream().sorted().count();
        System.out.println(count);
        long t1 = System.nanoTime();

        long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
        System.out.println(String.format("Parallel sort took: %d ms", millis));
    }
}
